<?php

namespace App\Model\Admin;

use App\Constants\Rbac\AdminCode;
use App\Model\CrudModel;

/**
 * @property int $id
 * @property string $account
 * @property string $nickname
 * @property int is_root 原始值
 * @property bool $is_root_bool is_root的动态属性
 * @property array $role_ids
 */
class AdminModel extends CrudModel
{

    protected bool $softDel = true;

    protected ?string $table = 'admin';

    protected array $casts = [
        'role_ids' => 'array',
    ];

    protected array $adminPageListField = [
        'id',
        'account',
        'nickname',
        'is_root',
        'role_ids',
    ];

    public function addOne(array $data)
    {
        $now = time();
        return $this->insert([
            'deleted_at' => 0,
            'account' => $data['account'],
            'nickname' => $data['nickname'],
            'login_pwd' => $data['login_pwd'],
            'is_root' => $data['is_root'],
            'role_ids' => json_encode($data['role_ids'] ?? []),
            'created_at' => $now,
            'updated_at' => $now,
        ]);
    }

    public function updateById($id, array $data)
    {
        $upda = [
            'nickname' => $data['nickname'],
            'role_ids' => json_encode($data['role_ids'] ?? []),
            'updated_at' => time(),
        ];
        if (!empty($data['is_root'])){
            $upda['is_root'] = $data['is_root'];
        }
        return $this->buildQuery([
            'id' => $id,
        ])
            ->update($upda);
    }

    public function findByAcc(string $acc, $field = ['*'])
    {
        return $this->buildQuery([
            'account' => $acc,
        ])
            ->first($field);
    }

    public function updateLoginPwd($id, $hashPwd)
    {
        return $this->updateField(['id'=>$id,], 'login_pwd', $hashPwd);
    }

    public function getIsRootBoolAttribute()
    {
        return $this->is_root == AdminCode::IS_ROOT;
    }

    public function updateIsRoot($id, $isRoot)
    {
        return $this->updateField([
            'id' => $id,
        ],'is_root',$isRoot);
    }
}